<template>
	<view class="wrap">
		<u-form :model="cote" :rules="rules" ref="uForm" :errorType="errorType">
			<u-form-item label-position="top" label="所属畜舍" prop="houseName">
				<u-input type="select" :select-open="actionSheetShow" v-model="cote.houseName" placeholder="请选择所属畜舍" @click="actionSheetShow = true"></u-input>
			</u-form-item>
			<u-form-item label-width="120" label-position="top" label="畜栏名称" prop="coteName">
				<u-input placeholder="请输入畜栏名称" v-model="cote.coteName" type="text"></u-input>
			</u-form-item>
			<u-form-item label-position="top" label="备注" prop="remark">
				<u-input type="textarea" placeholder="请填写畜栏备注" v-model="cote.remark" />
			</u-form-item>
		</u-form>
		<u-button type="primary" @click="submit">保存</u-button>
		<u-action-sheet :list="houses" v-model="actionSheetShow" @click="actionSheetCallback"></u-action-sheet>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				houses: [],
				coteId: '',
				cote: {},
				rules: {
					coteName: [{
						required: true,
						message: '请输入畜栏名称',
						trigger: 'blur'
					}],
					houseName: [{
						required: true,
						message: '请选择所属畜舍',
						trigger: 'blur'
					}]
				},
				errorType: ['message'],
				actionSheetShow: false
			};
		},
		onLoad(e) {
			this.coteId = e.id
			this.loadCote()
			this.loadHouses()
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			loadCote: function() {
				this.$u.api.getCoteById(this.coteId).then(res => {
					const c = res.data;
					this.cote = {
						id: c.id,
						houseId: c.houseId,
						coteName: c.coteName,
						remark: c.remark
					}
				})
			},
			loadHouses: function() {
				this.$u.api.getHouses().then(res => {
					var houses = []
					res.data.forEach(e => {
						houses.push({
							text: e.houseName,
							value: e.id
						});
						if(e.id === this.cote.houseId){
							this.cote.houseName = e.houseName
						}
					})
					this.houses = houses
				})
			},
			actionSheetCallback: function(index) {
				this.cote.houseName = this.houses[index].text;
				this.cote.houseId = this.houses[index].value;
			},
			submit: function() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading()
						this.$u.api.editCote(this.cote).then(res => {
							this.$dm.showSuccess()
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						})
					}
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.wrap {
		padding: 30rpx;
	}

	.u-form {
		margin-bottom: 20px;
	}
</style>
